package com.mdz.myapplication.Controller;

import cn.hutool.core.util.ZipUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mdz.myapplication.Entity.*;
import com.mdz.myapplication.Mapper.*;
import com.mdz.myapplication.MyapplicationApplication;
import com.mdz.myapplication.View.FilelocView;
import com.mdz.myapplication.View.TempHzView;
import com.mdz.myapplication.utils.ReadFile;
import com.mdz.myapplication.utils.XmlGen;
import de.felixroske.jfxsupport.FXMLController;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.util.Callback;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.dom4j.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.*;

/**
 * <p>
 * 出入库汇总信息表 前端控制器
 * </p>
 *
 * @author 孟德志
 * @since 2021-11-07
 */
@FXMLController
public class TempHzController implements Initializable {

	@Autowired
	private TempHzMapper tempHzMapper;
	@Autowired
	private XsckMapper xsckMapper;
	@Autowired
	private CgrkMapper cgrkMapper;
	@Autowired
	private DdlxMapper ddlxMapper;
	@Autowired
	private XmlgsMapper xmlgsMapper;
	@Autowired
	private FilelocMapper filelocMapper;
	@FXML
	private CheckBox mSelectAll;
	@FXML
	private TableView<TempHz> tabel_view;
   	@FXML
	private TableColumn<TempHz, CheckBox> checkid;
	@FXML
	private TableColumn<TempHz,String> djlx_id,gsbh_id,Actor_id,rq_id,CorpOrderID_id,ksmc_id,dwmch_id,shfahr1_id,FromAddress_id,ToAddress_id;
	@FXML
	private TableColumn<TempHz,Integer> shuliang_id;
	@FXML
	private TableColumn xh_id;
	@FXML
	private Button setFileLoc;
	@FXML
	private Button refabtn;
	@Autowired
	private FilelocView filelocView;

	@FXML
	private MenuBar fileloc;

	@Value(value = "${gsbh}")
	private String gsbh;

	@Override
	public void initialize(URL location, ResourceBundle resources) {
		getinitdata();
	}

	/**
	 * 对checkbox勾选去勾选处理
	 */
	@FXML
	public void selectBox(){
		ObservableList<TempHz> items = tabel_view.getItems();
		if (mSelectAll.isSelected()){
			for (TempHz cxCadreInfo:items){
				cxCadreInfo.cb.getCheckBox().getValue().setSelected(false);
			}
		}else {
			for (TempHz cxCadreInfo:items){
				cxCadreInfo.cb.getCheckBox().getValue().setSelected(true);
			}
		}
	}
	@FXML
	public void check()
	{
		ObservableList<TempHz> lists=tabel_view.getItems();
		String ddh="";
		String djlx="";
		String gsbhs="";
		String rq="";
		Integer id=0;
		for(TempHz o:lists) {
			ddh=o.getCorpOrderID().trim();
			djlx=o.getDjlx().trim();
			gsbhs=o.getGsbh().trim();
			rq=o.getRq().trim();
			id=o.getId();
			if(o.cb.isSelected())
			{
				System.out.println(o.getCorpOrderID());
				System.out.println(o.getDjlx().substring(2,4));
				if (o.getDjlx().substring(2,4).equals("出库")){
					System.out.println("出库");
					File file = new File("C:\\Users\\app\\123.xml");
					BufferedReader reader = null;
					List<Xsck> xscks = new ArrayList<>();
					List<Ddlx> ddlxes = new ArrayList<>();
					List<Xmlgs> xmlgs = new ArrayList<>();
					List<String> ziduan = new ArrayList<>();
					String eventName = "";
					String mainaction = "";
					XmlGen dom4j = new XmlGen();
					Document document = null;
					StringBuffer chardoc=new StringBuffer();
					StringBuffer zfc = new StringBuffer();
					xscks = xsckMapper.selectList(new QueryWrapper<Xsck>().eq("CorpOrderID",ddh).eq("gsbh",gsbhs).eq("djlx",djlx));
					ddlxes = ddlxMapper.selectList(new QueryWrapper<Ddlx>().eq("ddlxmc", djlx));
					eventName = ddlxes.get(0).getEventName();
					mainaction = ddlxes.get(0).getMainaction();
					xmlgs = xmlgsMapper.selectList(new QueryWrapper<Xmlgs>().eq("eventname", eventName));
					try {
						reader = new BufferedReader(new FileReader(file));
						String tempString = null;
						int line = 1;
						// 一次读入一行，直到读入null为文件结束
						while ((tempString = reader.readLine()) != null) {
							if (line < 2) {
								zfc.append(tempString);
							}else if (line==2){
								tempString="<Document xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-instance\' xsi:noNamespaceSchemaLocation=\'终端接口XML Schema-3.0.xsd\' SN=\'323232323\' Version=\'3.0\' License=\'00120-100290-002\'>";
								zfc.append(tempString);
							} else if (line >= 3 && line <= 6) {
								if (tempString.contains("#eventname#")) {
									zfc.append(tempString.replace("#eventname#", eventName).replace("#mainaction#", mainaction));
								} else if (tempString.contains("#mainaction#")) {
									zfc.append(tempString.replace("#mainaction#", mainaction));
								} else {
									zfc.append(tempString);
								}
							} else if (line > 6) {
								if (tempString.contains("#Code[i]#")) {
									String zidname = "";
									StringBuffer orderNo = new StringBuffer();
									Class c = xscks.get(0).getClass();
									for (int k = 0; k < xmlgs.size(); k++) {
										zidname = xmlgs.get(k).getZidname();
										Object obj = null;
										for (int j = 0; j < xscks.size(); j++) {
											try {
												Field field = c.getDeclaredField(zidname);
												field.setAccessible(true);
												obj = xscks.get(j);
												if (j >= 0) {
													orderNo.append(",");
												}
												orderNo.append(field.get(obj));
											} catch (NoSuchFieldException e) {
												e.printStackTrace();
											} catch (IllegalAccessException e) {
												e.printStackTrace();
											}
										}
									}
									String[] shuzu = orderNo.substring(1).split(",");
									int count = shuzu.length % xscks.size() == 0 ? shuzu.length / xscks.size() : shuzu.length / xscks.size() + 1;
									List<List<String>> subAryList = new ArrayList<List<String>>();
									//按照获取的数组数循环
									for (int s = 0; s < count; s++) {
										//定位每组循环的最大下标
										int index = s * xscks.size();
										List<String> list = new ArrayList<String>();
										int j = 0;
										//j小于这一组的最大下标 而且小于整个大数组的长度  将这个符合条件的元素加入list.
										while (j < xscks.size() && index < shuzu.length) {
											list.add(shuzu[index++]);
											j++;
										}
										//然后再将list加入到大的list里面
										subAryList.add(list);
									}
									Object[] subAry = new Object[subAryList.size()];
									//循环遍历大List\
									for (int h = 0; h < subAryList.size(); h++) {
										List<String> subList = subAryList.get(h);
										String[] subAryItem = new String[subList.size()];
										//将小list里面的值遍历添加到小数组里面
										for (int j = 0; j < subList.size(); j++) {
											subAryItem[j] = subList.get(j);
										}
//                            System.out.println(Arrays.toString(subAryItem));
										//将小数组添加到大数组里
										subAry[h] = subAryItem;
									}
									String[] zidn = new String[xmlgs.size()];
									String[] head = new String[xmlgs.size()];
									String[] foot = new String[xmlgs.size()];
									for (int i = 0; i < xmlgs.size(); i++) {
										zidn[i] = xmlgs.get(i).getZidname();
										head[i] = xmlgs.get(i).getHead();
										foot[i] = xmlgs.get(i).getFoot();
									}
									for (int i = 0; i < xscks.size(); i++) {
										zfc.append("<Data");
										for (int j = 0; j < zidn.length; j++) {
											zfc.append(" " + zidn[j] + "=\"" + shuzu[i + (xscks.size() * j)].trim() + "\"");
										}
										zfc.append("/>");
									}
								} else {
									zfc.append(tempString);
								}
							}
							line++;
						}
						reader.close();
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
						if (reader != null) {
							try {
								reader.close();
							} catch (IOException e1) {
							}
						}
					}
					chardoc=zfc;
					document = dom4j.generateDocumentByString(chardoc.toString());
					String fileloc=filelocMapper.selectList(new QueryWrapper<Fileloc>().eq("gsbh",gsbhs).eq("leix","出库")).get(0).getFileloc();
					String newURL = fileloc.replaceAll("\\\\","/");
					String saveDocument = dom4j.saveDocument(document, new File(newURL + "/" + ddh + "_" + djlx + "_" + rq + "_" + gsbh + ".xml"));
					if (saveDocument=="成功"){
						tempHzMapper.updateisxz(ddh,gsbh,djlx);
					}else {
						Alert alert = new Alert(Alert.AlertType.INFORMATION);
						alert.setHeaderText("温馨提示");
						alert.setContentText(saveDocument);
						alert.showAndWait();
						return;
					}
				}else {
					System.out.println("入库");
					File file = new File("C:\\Users\\app\\123.xml");
					BufferedReader reader = null;
					List<Cgrk> xscks = new ArrayList<>();
					List<Ddlx> ddlxes = new ArrayList<>();
					List<Xmlgs> xmlgs = new ArrayList<>();
					List<String> ziduan = new ArrayList<>();
					String eventName = "";
					String mainaction = "";
					XmlGen dom4j = new XmlGen();
					Document document = null;
					StringBuffer chardoc=new StringBuffer();
					StringBuffer zfc = new StringBuffer();
					xscks = cgrkMapper.selectList(new QueryWrapper<Cgrk>().eq("CorpOrderID",ddh).eq("gsbh",gsbhs).eq("djlx",djlx));
					ddlxes = ddlxMapper.selectList(new QueryWrapper<Ddlx>().eq("ddlxmc", djlx));
					eventName = ddlxes.get(0).getEventName();
					mainaction = ddlxes.get(0).getMainaction();
					xmlgs = xmlgsMapper.selectList(new QueryWrapper<Xmlgs>().eq("eventname", eventName));
					try {
						reader = new BufferedReader(new FileReader(file));
						String tempString = null;
						int line = 1;
						// 一次读入一行，直到读入null为文件结束
						while ((tempString = reader.readLine()) != null) {
							if (line < 2) {
								zfc.append(tempString);
							}else if (line==2){
								tempString="<Document xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-instance\' xsi:noNamespaceSchemaLocation=\'终端接口XML Schema-3.0.xsd\' SN=\'323232323\' Version=\'3.0\' License=\'00120-100290-002\'>";
								zfc.append(tempString);
							} else if (line >= 3 && line <= 6) {
								if (tempString.contains("#eventname#")) {
									zfc.append(tempString.replace("#eventname#", eventName).replace("#mainaction#", mainaction));
								} else if (tempString.contains("#mainaction#")) {
									zfc.append(tempString.replace("#mainaction#", mainaction));
								} else {
									zfc.append(tempString);
								}
							} else if (line > 6) {
								if (tempString.contains("#Code[i]#")) {
									String zidname = "";
									StringBuffer orderNo = new StringBuffer();
									Class c = xscks.get(0).getClass();
									for (int k = 0; k < xmlgs.size(); k++) {
										zidname = xmlgs.get(k).getZidname();
										Object obj = null;
										for (int j = 0; j < xscks.size(); j++) {
											try {
												Field field = c.getDeclaredField(zidname);
												field.setAccessible(true);
												obj = xscks.get(j);
												if (j >= 0) {
													orderNo.append(",");
												}
												orderNo.append(field.get(obj));
											} catch (NoSuchFieldException e) {
												e.printStackTrace();
											} catch (IllegalAccessException e) {
												e.printStackTrace();
											}
										}
									}
									String[] shuzu = orderNo.substring(1).split(",");
									int count = shuzu.length % xscks.size() == 0 ? shuzu.length / xscks.size() : shuzu.length / xscks.size() + 1;
									List<List<String>> subAryList = new ArrayList<List<String>>();
									//按照获取的数组数循环
									for (int s = 0; s < count; s++) {
										//定位每组循环的最大下标
										int index = s * xscks.size();
										List<String> list = new ArrayList<String>();
										int j = 0;
										//j小于这一组的最大下标 而且小于整个大数组的长度  将这个符合条件的元素加入list.
										while (j < xscks.size() && index < shuzu.length) {
											list.add(shuzu[index++]);
											j++;
										}
										//然后再将list加入到大的list里面
										subAryList.add(list);
									}
									Object[] subAry = new Object[subAryList.size()];
									//循环遍历大List\
									for (int h = 0; h < subAryList.size(); h++) {
										List<String> subList = subAryList.get(h);
										String[] subAryItem = new String[subList.size()];
										//将小list里面的值遍历添加到小数组里面
										for (int j = 0; j < subList.size(); j++) {
											subAryItem[j] = subList.get(j);
										}
//                            System.out.println(Arrays.toString(subAryItem));
										//将小数组添加到大数组里
										subAry[h] = subAryItem;
									}
									String[] zidn = new String[xmlgs.size()];
									String[] head = new String[xmlgs.size()];
									String[] foot = new String[xmlgs.size()];
									for (int i = 0; i < xmlgs.size(); i++) {
										zidn[i] = xmlgs.get(i).getZidname();
										head[i] = xmlgs.get(i).getHead();
										foot[i] = xmlgs.get(i).getFoot();
									}
									for (int i = 0; i < xscks.size(); i++) {
										zfc.append("<Data");
										for (int j = 0; j < zidn.length; j++) {
											zfc.append(" " + zidn[j] + "=\"" + shuzu[i + (xscks.size() * j)].trim() + "\"");
										}
										zfc.append("/>");
									}
								} else {
									zfc.append(tempString);
								}
							}
							line++;
						}
						reader.close();
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
						if (reader != null) {
							try {
								reader.close();
							} catch (IOException e1) {
							}
						}
					}
					chardoc=zfc;
					document = dom4j.generateDocumentByString(chardoc.toString());
					String fileloc=filelocMapper.selectList(new QueryWrapper<Fileloc>().eq("gsbh",gsbhs).eq("leix","入库")).get(0).getFileloc();
					String newURL = fileloc.replaceAll("\\\\","/");
					String saveDocument = dom4j.saveDocument(document, new File(newURL+"/" + ddh + "_" + djlx + "_" + rq+"_"+gsbh+".xml"));
					if (saveDocument=="成功"){
						tempHzMapper.updateisxz(ddh,gsbh,djlx);
					}else {
						Alert alert = new Alert(Alert.AlertType.INFORMATION);
						alert.setHeaderText("温馨提示");
						alert.setContentText(saveDocument);
						alert.showAndWait();
						return;
					}
				}
			}
		}
		getinitdata();
	}

	@FXML
	private void setFileLoc() {
//		MyapplicationApplication.showView(FilelocView.class, Modality.WINDOW_MODAL);
//		MyapplicationApplication.showView(FilelocView.class, Modality.WINDOW_MODAL);
//		Stage stage=new Stage(FilelocView.class);
//		stage.show();
//		setFileLoc.setOnAction(event -> {
//			filevbox.getChildren().add(filelocView.getView());
//		});
//

		Stage stage;
		stage=(Stage)fileloc.getScene().getWindow();
		stage.close();
		MyapplicationApplication.showView(FilelocView.class);


//		URL resource=getClass().getResource("/FileLoc.fxml");
//		System.out.println(resource.toString());
//		if (resource==null){
//			System.out.println("hello");
//			System.exit(0);
//		}else {
//			System.out.println("zhaodaole");
//		}
//
//		try {
//			Stage stage;
//			stage=(Stage)setFileLoc.getScene().getWindow();
//			Parent root = FXMLLoader.load(getClass().getResource("/FileLoc.fxml"));
//			Scene scene = new Scene(root);
//			stage.setScene(scene);
////			stage.setResizable(true);
//			stage.show();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
	}


	public void exitapp() {
//		MyapplicationApplication.getStage().setTitle("smqk");
//		Platform.exit();
		try {
			String s1 = ReadFile.readTxt(new File("C:\\Users\\app\\app.ini"));
			System.out.println(s1.split("=")[1]);
//			System.out.println(ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX));
//			String s2 = ReadFile.readTxt(ResourceUtils.getFile("classpath:app.ini"));
//			System.out.println(s2);
			String apploc = System.getProperty("user.dir");
			System.out.println(System.getProperty("os.version"));
			Alert alert = new Alert(Alert.AlertType.INFORMATION);
			alert.setHeaderText("温馨提示");
			alert.setContentText(apploc);
			alert.showAndWait();
//			request.getServletContext().getRealPath("/");
			} catch (IOException e) {
				e.printStackTrace();
			}
	}

	public void getinitdata(){
		List<TempHz> tempHzs=tempHzMapper.getlist(gsbh);
		ObservableList<TempHz> list = FXCollections.observableArrayList(tempHzs);
		djlx_id.setCellValueFactory(new PropertyValueFactory("djlx"));
		gsbh_id.setCellValueFactory(new PropertyValueFactory("gsbh"));
		Actor_id.setCellValueFactory(new PropertyValueFactory("Actor"));
		rq_id.setCellValueFactory(new PropertyValueFactory("rq"));
		CorpOrderID_id.setCellValueFactory(new PropertyValueFactory("CorpOrderID"));
		ksmc_id.setCellValueFactory(new PropertyValueFactory("ksmc"));
		dwmch_id.setCellValueFactory(new PropertyValueFactory("dwmch"));
		shfahr1_id.setCellValueFactory(new PropertyValueFactory("shfahr1"));
		shuliang_id.setCellValueFactory(new PropertyValueFactory("shuliang"));
		FromAddress_id.setCellValueFactory(new PropertyValueFactory("FromAddress"));
		ToAddress_id.setCellValueFactory(new PropertyValueFactory("ToAddress"));
		CorpOrderID_id.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getCorpOrderID()) );
		checkid.setCellValueFactory(cellData ->cellData.getValue().cb.getCheckBox());
		xh_id.setCellFactory((col) -> {
			TableCell<TempHz, String> cell = new TableCell<TempHz, String>() {
				@Override
				public void updateItem(String item, boolean empty) {
					super.updateItem(item, empty);
					this.setText(null);
					this.setGraphic(null);
					if (!empty) {
						int rowIndex = this.getIndex() + 1;
						this.setText(String.valueOf(rowIndex));
					}
				}
			};
			cell.setAlignment(Pos.CENTER);
			return cell;
		});
		tabel_view.setItems(list);
		checkid.setCellValueFactory(cellData ->cellData.getValue().cb.getCheckBox());
		//初始化复选框-监听-所有checkbox复选框都勾选则全选框勾选，所有checkbox复选框不勾选则全选框不勾选
		javafx.util.Callback<TableColumn<TempHz, CheckBox>, TableCell<TempHz, CheckBox>> cellFactory1 =
				new Callback<TableColumn<TempHz, CheckBox>, TableCell<TempHz, CheckBox>>() {
					@Override
					public TableCell call(TableColumn p) {
						TableCell cell = new TableCell<person, CheckBox>() {
							@Override
							public void updateItem(CheckBox item, boolean empty) {
								super.updateItem(item, empty);
								setGraphic(item);
								if (item!= null) {
									item.selectedProperty().addListener(new ChangeListener<Boolean>() {
										@Override
										public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
											boolean booSelectAll = true;
											ObservableList<TempHz> items2 = tabel_view.getItems();
											for (TempHz cxCadreInfo2:items2){
												if (!cxCadreInfo2.cb.isSelected()) {
													booSelectAll = false;
													break;
												}
											}
											mSelectAll.setSelected(booSelectAll);
										}
									});
								}
							}
						};
						return cell;
					}
				};
		checkid.setCellFactory(cellFactory1);
	}

	public void refa(){
		getinitdata();
	}
}

